/**
 *  @desc 单选
 */
import React, { useEffect, useState } from 'react';
import { Checkbox } from 'antd';
import { getTempData } from "../_common/wrapXhr";

interface ICheckBoxProps {
  api?: {
    url?: string;
    params?: string;
    type: 'POST';
  };//接口参数，包含（url:接口地址，params:发送的数据，一旦发送数据默认GET）
  dataSource?: Array<any>;//显示的数据，格式 ：['选项一', '选项二'] 或 [{ name: '选项一', code: 1 }, { name: '选项二', code: 2 }];
  map?: {
    text: string;
    value: string;
  }
  onChange: (a: any) => {}; // 设置onChange函数
  editable: Boolean
  [key: string]: any;
}
const CustomCheckbox: React.FC<ICheckBoxProps> = (props: any) => {
  const { api, dataSource, map, onChange, editable = true } = props;
  const [options, setOptions] = useState<any>([]);
  useEffect(() => {
    if (api) {
      getData(api);
    } else {
      return;
    }
  }, [api])
  useEffect(() => {
    if (Array.isArray(dataSource) && dataSource.length) {
      setOptions(dataSource)
    }
  }, [
    JSON.stringify(dataSource)
  ])
  const getData = async (api: any) => {
    try {
      if (api?.url) {
        const data: any = await getTempData(api);
        if (map) {
          data.map((i: any) => {
            return {
              label: i[map.text as any],
              value: i[map.value as any],
            }
          })
        }
        setOptions(data);
      }
    } catch (err) {
      console.warn(`scheck-box组件-getData发生错误:${err}`)
    }
  }
  const onChangeCheck = (val: any) => {
    onChange && onChange(val);
  }
  return editable ? <Checkbox.Group {...props} options={options} onChange={onChangeCheck} /> : <Checkbox.Group {...props} options={options} disabled={true} />
}


export default CustomCheckbox;